Kotlin 有內建單例,只要把class
換成object
就好
object Member {
private var name: String = ""
fun setMemberName(name: String) {
this.name = name
}
fun getMemberName(): String {
return name
}
}
Member.setMemberName("AndyAWD")
Log.d("TAG", "姓名: ${Member.getMemberName()}")
但是內建的單例是餓漢式
我們精英中心.jpg
class Member {
companion object {
val INSTANCE = MemberHolder.memberHolder
}
private object MemberHolder {
val memberHolder = Member
}
}